package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 设备管理Service业务层处理
 * 
 * @author laoYe
 * @date 2025-01-04
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //1. 查询阿里云平台所有的产品
        // 请求对象
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setPageSize(200);//设备每页大小
        queryProductListRequest.setCurrentPage(1);//查询第1页
        //设置要查询的哪个实例的数据
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        // 发送查询请求
        QueryProductListResponse queryProductListResponse = null;
        try {
            queryProductListResponse = client.queryProductList(queryProductListRequest);
            if (queryProductListResponse.getBody().success) {
                //2. 转成json字符串后存入redis
                String jsonStr = JSONUtil.toJsonStr(queryProductListResponse.getBody().getData().getList().getProductInfo());
                stringRedisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL,jsonStr);
                return;
            }
        } catch (Exception e) {
            log.error("同步阿里云平台产品列表失败",e);
        }
        throw new ServiceException("同步阿里云平台产品列表失败");
    }

    /**
     * 查询所有的产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProducts() {
        String jsonStr = stringRedisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        if(StrUtil.isEmpty(jsonStr)){
            throw new ServiceException("请先同步产品数据!");
        }
        List<ProductVo> productVoList = JSONUtil.toList(jsonStr, ProductVo.class);
        return productVoList;
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //1.设备名称是否重复
        Long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count>0) {
            //存在了
            throw new ServiceException("设备名称已存在!");
        }
        //2.IOT新增设备
        String iotId = addIotDevice(deviceDto);
        device.setIotId(iotId);
        //3.查询产品  设置产品名称到设备对象, 从redis中取出对应的产品名称
        setProductName(device);

        //4.位置类型是否是0
        if (ObjectUtil.equal(deviceDto.getLocationType(),0)) {
            //随身设备
            device.setPhysicalLocationType(-1);//老人的设备
        }
        //5.保存到数据是否成功
        try {
            device.setHaveEntranceGuard(0);//没有门禁
            save(device);
        } catch (Exception e) {
            log.error("新增设备失败",e);
            //6.如果保存失败要删除IOT平台上的设备
            deleteIotDevice(device);
            throw new ServiceException("新增设备失败");
        }

    }

    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //1. 数据的
        Device device = lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()).one();
        DeviceVo vo = BeanUtil.toBean(device, DeviceVo.class);
        //2. Iot平台上的
        setIotDeviceDetail(vo);
        return vo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param request
     * @return
     */
    @Override
    public R queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            QueryThingModelPublishedResponse queryThingModelPublishedResponse = client.queryThingModelPublished(request);
            if (queryThingModelPublishedResponse.getBody().success) {
                return R.ok(queryThingModelPublishedResponse.getBody().getData());
            }
        } catch (Exception e) {
            log.error("查询产品的物模型数据失败", e);
        }
        throw new RuntimeException("查询产品的物模型数据失败");
    }

    /**
     * 查询设备最新数据
     *
     * @param request
     * @return
     */
    @Override
    public R queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        try {
            QueryDevicePropertyStatusResponse queryDevicePropertyStatusResponse = client.queryDevicePropertyStatus(request);
            if (queryDevicePropertyStatusResponse.getBody().success) {
                return R.ok(queryDevicePropertyStatusResponse.getBody().getData());
            }
        } catch (Exception e) {
            log.info("查询设备最新数据失败", e);
        }
        throw new ServiceException("查询设备最新数据失败");
    }

    /**
     * 设置iot平台上的设备信息
     * @param vo
     */
    private void setIotDeviceDetail(DeviceVo vo) {
        QueryDeviceDetailRequest deviceDetailRequest = new QueryDeviceDetailRequest();
        deviceDetailRequest.setProductKey(vo.getProductKey());
        deviceDetailRequest.setIotId(vo.getIotId());
        deviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        try {
            QueryDeviceDetailResponse queryDeviceDetailResponse = client.queryDeviceDetail(deviceDetailRequest);
            if (queryDeviceDetailResponse.getBody().success) {
                BeanUtil.copyProperties(queryDeviceDetailResponse.getBody().getData(),vo);
            }
        } catch (Exception e) {
            log.error("查询Iot设备详情失败", e);
            throw new ServiceException("查询Iot设备详情失败");
        }
    }

    /**
     * 删除IOT平台上的设备
     * @param device
     */
    private void deleteIotDevice(Device device) {
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setProductKey(device.getProductKey());
        deleteDeviceRequest.setIotId(device.getIotId());
        deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        try {
            DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
            if (deleteDeviceResponse.getBody().success) {
                return;
            }
        } catch (Exception e) {
            log.error("删除Iot平台设备失败!",e);
        }
        throw new ServiceException("删除Iot平台设备失败!");
    }

    /**
     * 设置产品的名称
     * @param device
     */
    private void setProductName(Device device) {
        List<ProductVo> productVos = allProducts();
        productVos.stream().filter(p-> ObjectUtil.equal(device.getProductKey(), p.getProductKey()))
            //找第一个
            .findFirst()
            // 如果能找到，有一个
            .ifPresent(vo->device.setProductName(vo.getProductName()));
        /*for (ProductVo productVo : productVos) {
            if(device.getProductKey().equals(productVo.getProductKey())){
                device.setProductName(productVo.getProductName());
            }
        }*/
    }

    /**
     * IOT新增设备
     * @param deviceDto
     * @return
     */
    private String addIotDevice(DeviceDto deviceDto) {
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        try {
            RegisterDeviceResponse registerDeviceResponse = client.registerDevice(registerDeviceRequest);
            if (registerDeviceResponse.getBody().success) {
                String iotId = registerDeviceResponse.getBody().getData().getIotId();
                log.info("新增的设备{}, iotId={}", deviceDto.getDeviceName(), iotId);
                return iotId;
            }
        } catch (Exception e) {
            log.error("IOT新增设备失败", e);
        }
        throw new ServiceException("IOT新增设备失败");
    }
}
